package com.itheima.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.config.RestHighLevelClientConfig;
import com.itheima.mapper.SkuMapper;
import com.itheima.pojo.GoodsVo;
import com.itheima.pojo.Sku;
import com.itheima.service.SkuService;
import com.itheima.support.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    @Autowired
    RestHighLevelClientConfig restHighLevelClient;


    public PageResult findAll(GoodsVo goodsVo) {
        //初始化
        RestHighLevelClient client = restHighLevelClient.init();

        //2. 创建SearchRequest对象，并制定索引库名称
        SearchRequest request = new SearchRequest("sku");


        //1. 创建SearchSourceBuilder对象  {}
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //创建Bool查询条件，在商品标题上检索
        BoolQueryBuilder boolQuery = null;
        if (!goodsVo.getDetail().equals("")) {
            boolQuery = QueryBuilders.boolQuery();
            MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("name", goodsVo.getDetail());
            boolQuery.must(queryBuilder);
        }


        //判断价格参数是否存在
        if (goodsVo.getPrice() != null) {
            String[] prices = goodsVo.getPrice().split("-");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");

            if(prices.length==1){
                rangeQuery.gte(prices[0]);
            }else {
                rangeQuery.gte(prices[0]).lte(prices[1]);
            }

            boolQuery.filter(rangeQuery);
        }

        searchSourceBuilder.query(boolQuery);


        //设置价格排序查询
        //降序查询
        if(goodsVo.getSort()==1){
          searchSourceBuilder.sort("price",SortOrder.DESC);
        }
        //升序查询
        if(goodsVo.getSort()==0) {
            searchSourceBuilder.sort("price",SortOrder.ASC);
        }


        // 设置 createTime 排序
        if(goodsVo.getCreateTime()!=null){
            searchSourceBuilder
                    .sort("createTime", SortOrder.DESC);
        }


        // 设置分页查询
        searchSourceBuilder.from(Integer.parseInt(goodsVo.getPage())).size(Integer.parseInt(goodsVo.getSize()));


        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");  // 要显示高亮的域
        highlightBuilder.preTags("<font style='color:red'>"); // 前缀
        highlightBuilder.postTags("</font>"); // 后缀
        searchSourceBuilder.highlighter(highlightBuilder);

        //添加SearchSourceBuilder对象到source中
        request.source(searchSourceBuilder);


        //执行查询
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //解析结果并且解析商品高亮字段
        SearchHits searchHits = searchResponse.getHits();
        long total = searchHits.getTotalHits().value;
        System.out.println("总记录数： " + total);

        //   2. 获取SearchHits数组，并遍历
        SearchHit[] hits = searchHits.getHits();
        List<Sku> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            String userJson = hit.getSourceAsString();

            Sku sku = JSON.parseObject(userJson, Sku.class);

            //解析高亮的结果
            HighlightField highlightField = hit.getHighlightFields().get("name");
            if(highlightField!=null){
                Text[] fragments = highlightField.getFragments();// 高亮的片段， 100

                String nameFiled = StringUtils.join(fragments);  // 高亮结果
                sku.setName(nameFiled);
            }

            System.out.println(sku);
            list.add(sku);
        }
            return new PageResult(total,list);
    }
}
